package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.FileTransfers;
import com.gxnu.edu.cn.ttxxt.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/files")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,
                                      @RequestParam Long senderId,
                                      @RequestParam Long receiverId,
                                      @RequestParam(defaultValue = "false") boolean isGroup) {
        try {
            FileTransfers fileTransfers = fileService.uploadFile(senderId, receiverId, file, isGroup);
            return ResponseEntity.ok(fileTransfers);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件上传失败");
        }
    }

    @GetMapping("/{fileId}")
    public ResponseEntity<?> getFileInfo(@PathVariable Long fileId) {
        FileTransfers fileTransfers = fileService.getFileById(fileId);
        return ResponseEntity.ok(fileTransfers);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserFiles(@PathVariable Long userId) {
        List<FileTransfers> files = fileService.getUserFiles(userId);
        return ResponseEntity.ok(files);
    }

    @GetMapping("/download/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long fileId) {
        try {
            FileTransfers fileTransfers = fileService.getFileById(fileId);
            byte[] fileContent = fileService.downloadFile(fileId);
            
            ByteArrayResource resource = new ByteArrayResource(fileContent);
            
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileTransfers.getFileName() + "\"")
                .contentLength(fileTransfers.getFileSize())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}
    